package com.ryskoo.permission.manager.repository;

import com.ryskoo.common.constant.CacheConstant;
import com.ryskoo.framework.core.repository.BasicRedisImpl;
import com.ryskoo.framework.core.utils.RedisUtil;
import com.ryskoo.permission.manager.domain.ManagerPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;

@Primary
@Repository
public class ManagerRedisImpl extends BasicRedisImpl<ManagerPO> implements IManagerRepository {
	@Autowired
	private RedisUtil redisClient;

	@Autowired
	private IManagerRepository managerRepository;

	@PostConstruct
	public void init() {
		this.setRedisClient(redisClient);
		this.setDao(managerRepository);
	}
	
	public ManagerRedisImpl() {
		super(CacheConstant.PMS_MANAGER_KEY);
	}
	
	/**
	 * 重写更新方法，根据管理员登录名获取管理员的缓存要刷新
	 * @param m
	 */
	@Override
	public void update(ManagerPO manager) {
		//刷新缓存
		redisClient.setObject(CacheConstant.PMS_MANAGER_KEY + manager.getLoginName(), manager);
		super.update(manager);
	}

    /**
     * 根据用户名查询管理员信息
     *
     * @param userName
     * @return
     */
    @Override
    public ManagerPO getManagerByLoginName(String userName) {
        //通过用户名先从缓存获取
        Object object = redisClient.getObject(CacheConstant.PMS_MANAGER_KEY + userName, ManagerPO.class);
        if (object != null) {
            return (ManagerPO) object;
        }
        //根据用户名查询管理员
        ManagerPO manager = managerRepository.getManagerByLoginName(userName);
        if (manager != null) {
            redisClient.setObject(CacheConstant.PMS_MANAGER_KEY + userName, manager);
            return manager;
        }
        
        return null;
     }
    
	/**
	 * 根据用户名查询管理员uuid
	 *
	 * @param userName
	 * @return
	 */
	@Override
	public String getManagerUuidByLoginName(String userName) {
		return managerRepository.getManagerUuidByLoginName(userName);
	}
}
